<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';

import { Page ,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import Draggable from 'vuedraggable';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
  Input,
  Textarea
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo_news, postPage_news, putPage_news } from '#/api/portal/vechilebanner';
import { usePreferencesStore } from '#/store';
import Upload from "#/components/Upload";
const bannerOptions = ref([])
import { getPage_news as getPage_banner } from '#/api/portal/carmodel';
const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `No.${index.value} - 编辑${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);




const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    post_title: '',
    post_alias: '',
    more: {
      thumbnail: '',
    },
    icon:[],
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,

  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    labelWidth: 200,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },

    {
        component: 'Select',
        fieldName: 'car_model',
        label: `车型`,
        componentProps: {
            class: 'w-full',
            placeholder: '选择车型',
            options: bannerOptions,
            allowClear: true,
            // showSearch: true,
            filterOption: false, // 不使用本地过滤
           // onSearch: handleSearch, // ✅ 绑定搜索触发事件
        },
      
    },  

    
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.news_title;
          state.form.title = values.title;
          state.form.content = values.content;
          state.form.icon = values.icon;
          state.form.images = values.images;
          state.form.background = values.background;
           state.form.car_model = values.car_model;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'content',
          'icon',
          'images',
          'background',
          'car_model'
        ],
      },
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'title',
      label: `${routeTitle}标题`,
       rules: z.string().max(30,'标题不能超过30'),
    },
 

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'content',
      label: `${routeTitle}描述`,
    },

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'images',
      label: `${routeTitle}车型图片`,
    },
     {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'background',
      label: `${routeTitle}背景图`,
    },
    {
      component: 'icon',
      defaultValue: [{title:'',images:[{'url':'','id':''}]}],
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'icon',
       label: `${routeTitle}图标`,
    },




  ],
});

async function onSubmit() {
   updateForm();
  const values: any = state.form;

  let response;

  if (values.id) {
    response = await putPage_news(values);
  } else {
    delete values.id;
    response = await postPage_news(values);
  }

  const { code, msg } = response;

  if (code === 1) {
    message.success(msg || '操作成功');
    closeCurrentTab();
    // router.push({ name: 'Portalvechilebanner' });
    router.back(); // ✅ 返回上一页
  } else {
    message.error(msg || '操作失败'); 
  }
}


async function onGetPage(id: number) {
  const { data } = await getPageInfo_news({ id });
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    content: data?.content ?? '',
    icon: data?.icon ?? [{title:'',images:[{'url':'','id':''}],is_checked:false}],
    images: data?.images ?? [],
    background: data?.background ?? [],
    car_model:data?.car_model??''
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  const icon = data.post.icon;
  contentList.value = Array.isArray(icon) &&icon.length > 0 &&!(icon.length === 1 && icon[0] === '') ? JSON.parse(JSON.stringify(icon)) : [{ title: '', images: [{ url: '', id: '' }], is_checked: false }];
  state.pageThemeFiles = data.pageThemeFiles;
}

onMounted(async () => {
  if(index.value>0){
          await onGetPage(index.value);
  }



const res1 = await getPage_banner({car_model:(index.value>0?index.value:-1)});
  bannerOptions.value=(res1?.data?.list || []).map(item => ({
    label: item.category_name+' '+item.name,
    value: item.id,
  }))

  console.log(bannerOptions,'bannerOptions')

const handleSearch = async (value) => {
 const res1 = await getPage_banner({keyword:value,page:1,limit:15});
  bannerOptions.value=(res1?.data?.list || []).map(item => ({
    label: item.category_name+' '+item.name,
    value: item.id,
  }))
  

}



  
  
});




const contentList = ref([
  { title: '', images: [{ url: '/upload//default/20250703/bfed90791eaeac65cc3d5ed094dab3a9.png', id: 639 }]},
  { title: '', images: [{ url: '/upload/default/20250703/d5c32642870d928e82e4613b7bf34ba2.png', id: 638 }]},
  { title: '', images: [{ url: '/upload/default/20250703/cbfebdb526acfc54c4175785cf41f78a.png', id: 637 }]},
  { title: '', images: [{ url: '/upload/default/20250703/f282d836d3948947263edb1c3b3bafd9.png', id: 636 }]},
  { title: '', images: [{ url: '/upload/default/20250703/a72197ad6bcf2da372dc88bd25274bb2.png', id: 635 }]}
]);


function onUpdateName(index, value) {
  console.log(index);
  console.log(value);
  contentList.value[index].title = value
  updateForm()
}

// 更新 content

function createContentItem() {
  return {
    title: '',
    images: [{ url: '', id: '' }],
    is_checked: false
  };
}

function addContentItem() {
  contentList.value.push(createContentItem());
  updateForm();
}
function removeContentItem(index) {
    if (contentList.value.length <= 1) {return;}
  contentList.value.splice(index, 1) // 删除指定下标的项
  updateForm()                       // 同步到表单
}


// 同步到表单字段
function updateForm() {
  state.form.icon = JSON.parse(JSON.stringify(contentList.value));
  //BasicFormApi.setFieldValue('icon', JSON.parse(JSON.stringify(contentList.value))) // 深拷贝同步表单

}


</script>

<template>
  <Page>
    <Card :title="`${routeTitle}详情`">
      <BasicForm>
        
        <template #icon>
          <div class="content_s">
                <Card>
                   <Draggable v-model="contentList" item-key="id"  handle=".cursor-pointer" class="grid grid-cols-3 gap-6 tubiao">
                        <template #item="{ element, index }">
                          <div class="flex gap-4 items-start" style="marginc-top: 16px; padding: 16px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);    flex-direction: column;">
                            <!-- 图片上传 -->
                            <Upload
                              list-type="picture-card"
                              v-model="element.images"
                              :tips="'尺寸:50x50px,size:100K以内'"
                              style="flex-shrink: 0;"
                            />

                            <div class="flex flex-col gap-3 w-full">
                              <!-- 标题输入 -->
                              <Textarea
                                v-model:value="element.title"
                                placeholder="请输入标题"
                                class="w-full"
                                minHeight="200"
                                maxlength="250"
                                @input="onUpdateName(index, element.title)"
                              />

                              <!-- 删除按钮 -->
                              <div class="flex gap-6 justify-end items-center">
                                <Button danger type="dashed" @click="removeContentItem(index)">删除</Button>
                                <Button type="dashed" @click="addContentItem">添加</Button>
                                <Icon icon="ri:menu-2-line"  class="cursor-pointer"  title="点击拖动" />
                              </div>
                            </div>
                          </div>
                        </template>
                      </Draggable>
                       


                        
                 </Card>




             

               <div>
                
               
               </div>
          </div>  
          
          
        </template>


      </BasicForm>
    </Card>
  </Page>
</template>


<style scoped>

 :deep(.ant-upload-list-item-container) {
     width: 50px !important;
      height: 50px !important;
  }

  :deep(.upload-init-me){
    width: 50px !important;
    height: 50px !important;
  }
  :deep(.tubiao .ant-upload-wrapper.ant-upload-picture-card-wrapper 
  .ant-upload-list.ant-upload-list-picture-card 
  .ant-upload-list-item-container) {
  background-color: red;
}

</style>